package com.example.workmanagerdemo

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import androidx.work.*
import kotlinx.android.synthetic.main.activity_main.*

const val INPUT_DATA_KEY = "input_data_key"
const val OUTPUT_DATA_KEY = "out_data_key"
const val WORK_A_NAME = " work_a_name"
const val WORK_B_NAME = " work_b_name"
const val SHARED_PREFERENCES_NAME = "shp_name"

class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

    private val workManager = WorkManager.getInstance(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sharedPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
        sharedPreferences.registerOnSharedPreferenceChangeListener(this)
    }

    fun click(view: View) {

        val workRequestA = createWork(WORK_A_NAME)
        val workRequestB = createWork(WORK_B_NAME)
//        workManager.enqueue(workRequestA)    //只有一个情况下这样写
        workManager.beginWith(workRequestA).then(workRequestB).enqueue()

        //可以时时监听worker的工作变化情况
        workManager.getWorkInfoByIdLiveData(workRequestA.id).observe(this, Observer {
            Log.e("MyWork", "oncreate ${it.state}")
            if (it.state == WorkInfo.State.SUCCEEDED) {
                Log.e("MyWork", "oncreate ${it.outputData.getString(OUTPUT_DATA_KEY)}")
            }
        })
    }

    private fun createWork(name: String): OneTimeWorkRequest {

        //约束条件
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)//当网络一连接时候就开始执行任务
            .build()
        return OneTimeWorkRequestBuilder<MyWork>()
            .setConstraints(constraints)
            .setInputData(workDataOf(INPUT_DATA_KEY to name))
            .build()
    }

    fun updateData() {
        textView.text = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getInt(
            WORK_A_NAME, 0
        ).toString();
        textView2.text = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getInt(
            WORK_B_NAME, 0
        ).toString();
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
        updateData()
    }
}